package com.github.ylt.utils;


import com.github.ylt.protocol.parser.SoapParser;
import com.github.ylt.protocol.request.Request;
import org.dom4j.DocumentException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RequestUtils {
    private RequestUtils() {}
    private static class SingletonHolder {
        private static final RequestUtils INSTANCE = new RequestUtils();
    }
    public static RequestUtils getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private final Pattern startLinePattern = Pattern.compile("(\\w+) \\/(.+?) (HTTP/[12]\\.\\d+)");
    private final Pattern headerFieldPattern = Pattern.compile("([^:]+): (.*)");

    public synchronized Request getHeaderFields(String message) {
        Matcher matcher = startLinePattern.matcher(message);
        Map<String,Object> headerFields = new HashMap<String,Object>();
        while (matcher.find()) {
            headerFields.put("METHOD", matcher.group(1));
            headerFields.put("PATH", matcher.group(2));
            headerFields.put("VERSION", matcher.group(3));
        }
        boolean b = matcher.find(0);
        if(b){
            Matcher matcher1 = headerFieldPattern.matcher(message);
            matcher1.region(matcher.end(), message.length());
            while (matcher1.find()) {
                headerFields.put(matcher1.group(1).replace("\r\n","").toUpperCase(Locale.ROOT), matcher1.group(2));
            }
        }
        String[] split = message.split("\r\n");
        String s = split[split.length - 1];
        HashMap<String, String> params = new HashMap<>();
        if (StringUtils.isNotEmpty(s) && split.length > 6) {
            try {
                params = SoapParser.parseSoapMessage(s);
            } catch (DocumentException e) {
                throw new RuntimeException(e);
            }
        }

        return new Request(headerFields,null,params);
    }

}
